<?php

declare(strict_types=1);

namespace App\Request\Admin;

use App\Model\Article;
use Hyperf\Contract\ValidatorInterface;
use Hyperf\Validation\Request\FormRequest;

class ReviewControversialRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'approved' => ['required', 'boolean'],
        ];
    }

    public function withValidator(ValidatorInterface $validator): void
    {
        $id = $this->route('id');

        $validator->after(function ($validator) use ($id) {
            $exists = Article::where('id', $id)
                ->where('status', 'review')
                ->exists();

            if (!$exists) {
                $validator->errors()->add('id', '指定文章不存在或不处于待审核状态');
            }
        });
    }
}
